package org.yunai.yfserver.event;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import java.util.List;
import java.util.Map;

/**
 * {@link EventDispatcher}的FactoryBean
 * User: yunai
 * Date: 13-5-12
 * Time: 下午2:46
 */
public class EventDispatcherFactoryBean implements FactoryBean<EventDispatcher>, InitializingBean {

    /**
     * 事件与监听者集合<br />
     * KEY: 类名<br />
     * VALUE: 该事件的监听者列表
     */
    private Map<String, List<IEventListener>> listeners;
    /**
     * 事件分发者
     */
    private EventDispatcher eventDispatcher;

    @Override
    public EventDispatcher getObject() throws Exception {
        return eventDispatcher;
    }

    @Override
    public Class<?> getObjectType() {
        return EventDispatcher.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void afterPropertiesSet() throws Exception {
        eventDispatcher = new EventDispatcher();
        for (Map.Entry<String, List<IEventListener>> entry : listeners.entrySet()) {
            Class<? extends IEvent> clazz = (Class<? extends IEvent>) Class.forName(entry.getKey());
            for (IEventListener listener : entry.getValue()) {
                eventDispatcher.register(clazz, listener);
            }
        }
        listeners.clear();
    }

    public void setListeners(Map<String, List<IEventListener>> listeners) {
        this.listeners = listeners;
    }
}
